from contextlib import asynccontextmanager
from fastapi import FastAPI, Depends
from sqlalchemy.orm import Session
from common.log import logger
from config import base_config
from models import get_db, init_db
from agent.llm import init_llm

# 全局变量存储LLM对象
llm_objects = {}

@asynccontextmanager
async def lifespan(app: FastAPI):
    # 应用启动时执行
    logger.info(f"[主应用] 🚀 {base_config.APP_NAME} API服务启动中...")
    
    # 初始化数据库
    try:
        init_db()
        logger.info("[主应用] 📊 数据库初始化完成")
    except Exception as e:
        logger.error(f"[主应用] ❌ 数据库初始化失败: {e}")
        raise
    
    # 初始化LLM对象
    try:
        llm, embeddings, cllm = init_llm(use_online=True)
        if llm is None or embeddings is None or cllm is None:
            logger.error("[主应用] ❌ LLM初始化失败")
            raise Exception("LLM初始化失败")
        
        # 存储到全局变量
        llm_objects['llm'] = llm
        llm_objects['embeddings'] = embeddings
        llm_objects['cllm'] = cllm
        
        logger.info("[主应用] 🤖 LLM对象初始化完成")
    except Exception as e:
        logger.error(f"[主应用] ❌ LLM初始化失败: {e}")
        raise
    
    logger.info(f"[主应用] ✅ {base_config.APP_NAME} API服务启动完成")
    yield
    
    # 应用关闭时执行
    logger.info(f"[主应用] 👋 {base_config.APP_NAME} API服务关闭中...")
    
    # 清理LLM对象
    llm_objects.clear()
    logger.info("[主应用] 🧹 LLM对象清理完成")
    
    logger.info(f"[主应用] ✅ {base_config.APP_NAME} API服务关闭完成")

# 创建主FastAPI应用实例，使用lifespan参数
app = FastAPI(
    title=f"{base_config.APP_NAME} API",
    description="Kumquat King Robot API服务",
    version="1.0.0",
    lifespan=lifespan
)

# LLM依赖注入函数
def get_llm():
    """获取LLM对象的依赖注入函数"""
    return llm_objects.get('llm')

def get_embeddings():
    """获取Embeddings对象的依赖注入函数"""
    return llm_objects.get('embeddings')

def get_cllm():
    """获取ChatLLM对象的依赖注入函数"""
    return llm_objects.get('cllm')

# 导入各个service的router
from service.kqk_service import kqk_router

# 注册所有router到主应用
app.include_router(kqk_router)

# 根路径健康检查
@app.get("/health", tags=["Health"])
async def health_check(db: Session = Depends(get_db)):
    """健康检查接口，同时验证数据库连接"""
    try:
        # 测试数据库连接
        db.execute("SELECT 1")
        db_status = "healthy"
    except Exception as e:
        logger.error(f"[健康检查] ❌ 数据库连接失败: {e}")
        db_status = "unhealthy"
    
    # 检查LLM状态
    llm_status = "healthy" if llm_objects.get('llm') is not None else "unhealthy"
    
    return {
        "message": f"{base_config.APP_NAME} API is running", 
        "status": "healthy" if db_status == "healthy" and llm_status == "healthy" else "unhealthy",
        "database": db_status,
        "llm": llm_status
    }

@app.get("/", tags=["Root"])
async def root():
    return {"message": f"Hello, {base_config.APP_NAME}", "status": "200"}